package com.jdd.modules.parkmonthly.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdd.common.api.vo.Result;
import com.jdd.common.util.RestTemplateUtils;
import com.jdd.modules.area.service.IParkAreaInfoService;
import com.jdd.modules.parkmonthly.entity.PermissionGroup;
import com.jdd.modules.parkmonthly.mapper.PermissionGroupMapper;
import com.jdd.modules.parkmonthly.service.IPermissionAreaService;
import com.jdd.modules.parkmonthly.service.IPermissionGroupService;
import com.jdd.modules.parkmonthly.vo.AddMonthlySpace;
import com.jdd.modules.parkmonthly.vo.TaskMonthlyPermissionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;


/**
 * @Description: 权限组表
 * @Author: jdd
 * @Date: 2021-11-09
 * @Version: V1.0
 */
@Service
@Slf4j
public class PermissionGroupServiceImpl extends ServiceImpl<PermissionGroupMapper, PermissionGroup> implements IPermissionGroupService {

    @Resource
    private IParkAreaInfoService parkAreaInfoService;
    @Resource
    private RestTemplateUtils restTemplateUtils;
    @Resource
    private PermissionGroupMapper mapper;
    @Resource
    @Lazy
    private IPermissionAreaService permissionAreaService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void obtainAdminMonthlyPermission(String parkCode) {
        try {
            AddMonthlySpace addMonthlySpace = new AddMonthlySpace();
            addMonthlySpace.setJudge(true);
            addMonthlySpace.setStr(parkCode);

            ResponseEntity<Result> post = restTemplateUtils.post("", addMonthlySpace, Result.class);
            Result body = post.getBody();
            String str = JSONObject.toJSONString(body.getResult());
            TaskMonthlyPermissionVO taskMonthlyPermissionVO = JSONObject.parseObject(str, TaskMonthlyPermissionVO.class);
            parkAreaInfoService.removeAllInfo();
            permissionAreaService.remove(null);
            mapper.delete(null);
            this.saveBatch(taskMonthlyPermissionVO.getPermissionGroupList());
            parkAreaInfoService.saveBatch(taskMonthlyPermissionVO.getParkAreaInfoList());
            permissionAreaService.saveBatch(taskMonthlyPermissionVO.getPermissionAreaList());

        }catch (Exception e){
            log.error("处理场端同步车位信息出现异常,进行数据回滚!", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }
    }

}
